package com.ihr360.payroll.service.salarytasklet.step.reader;

import com.google.common.collect.Lists;
import com.ihr360.expr.engine.DependencyEngine;
import com.ihr360.job.core.annotation.BeforeRead;
import com.ihr360.job.core.item.ItemReader;
import com.ihr360.job.core.item.NonTransientResourceException;
import com.ihr360.job.core.item.ParseException;
import com.ihr360.job.core.item.UnexpectedInputException;
import com.ihr360.job.core.repository.JobRepository;
import com.ihr360.job.core.scope.context.SimpleStepContext;
import com.ihr360.payroll.dao.StaffPayPeriodTermCalcContextRepository;
import com.ihr360.payroll.model.dto.salary.task.period.StaffPayPeriodTermCalcContext;
import com.ihr360.payroll.service.salarytasklet.step.SalaryCalcContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * 根据员工薪资档案获取分段信息
 * @author davidwei
 */
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
@Component
public class SalaryCalcContextInfoReader implements ItemReader<List<StaffPayPeriodTermCalcContext>> {
    private static final int CHUNK_SIZE = 50;

    final Logger logger = LoggerFactory.getLogger(DependencyEngine.class.getName());
    private SimpleStepContext simpleStepContext;

    @Autowired
    private JobRepository jobRepository;

    @Autowired
    private StaffPayPeriodTermCalcContextRepository staffPayPeriodTermCalcContextRepository;

    private SalaryCalcContext salaryCalcContext;

    private List<List<String>> partitions;

    private int cursor = 0;


    public void setSalaryCalcContext(SalaryCalcContext salaryCalcContext) {
        this.salaryCalcContext = salaryCalcContext;
    }

    @Override
    public List<StaffPayPeriodTermCalcContext> read() throws Exception, ParseException, NonTransientResourceException {
        if (cursor == 0) {
            List<? extends String> staffs = this.salaryCalcContext.salaryPlanStaffListItemWriter.getWrittenItems();
            List<String> cloneStaffs = new ArrayList<>();
            staffs.stream().forEach(s -> cloneStaffs.add(s));
            this.partitions = Lists.partition(cloneStaffs, CHUNK_SIZE);
        }
        if (cursor >= this.partitions.size()) {
            cursor = 0;
            return null;
        }
        List<String> subStaffIds = partitions.get(cursor);

        List<StaffPayPeriodTermCalcContext> contexts = staffPayPeriodTermCalcContextRepository.findByIdTermIdAndIdStaffIdIn(salaryCalcContext.getTermId(), subStaffIds);
        cursor++;
        return contexts;
    }

    @BeforeRead
    public void setSimpleStepContext(SimpleStepContext simpleStepContext) {
        this.simpleStepContext = simpleStepContext;
    }

}